<?php

namespace app\admin\model\order;

use app\admin\model\shop\Message;
use think\Model;
use traits\model\SoftDelete;

class GoodsOrderModel extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'goods_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'pay_time_text',
        'status_text',
        'cancel_time_text'
    ];


    public const TYPE_TS = 100;//Dine In  堂食
    public const TYPE_DB = 200;//Takeout 打包
    public const TYPE_WM = 300;//Delivery 外卖

    public const TYPE_ARRAY_TEXT = [
        self::TYPE_TS => 'Dine In',
        self::TYPE_DB => 'Takeout',
        self::TYPE_WM => 'Delivery',
    ];

    public const APY_METHOD_XJ = 100; // 现结
    public const APY_METHOD_XD = 200; // 先下单

    public const APY_METHOD_ARRAY_TEXT = [
        self::APY_METHOD_XJ => 'Now pay',
        self::APY_METHOD_XD => 'Payment later',
    ];

    public function getStatusList()
    {
        return \app\app\model\order\GoodsOrderModel::STATUS_ARRAY_TEXT;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getCancelTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['cancel_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCancelTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function shop()
    {
        return $this->belongsTo(Message::class, 'shop_id', 'id', [], 'LEFT')
            ->setEagerlyType(0);
    }


    public function info($order_id)
    {
        $info = $this->where('id', $order_id)->find();
        return $info;
    }


}
